package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.manager.inst.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.NetworkDigitalModelAttrHandler;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;

/**
 * Created by huanghaosheng on 2021/4/12 21:41
 */
@Service
@AttrHandler(NetworkDigitalModelAttrHandler.class)
public class NetworkDigitalModelAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    OperateInstAttrService operateInstAttrService;

    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {

        /**
         * 主产品的型号子产品、附件产品的型号同时修改
         */
        if (KiteStringUtils.equals(inst.getSpecId(), ProdCateUtil.getMainMemberProdId(ProdCateUtil.GIFT_SZDJ_PROD))) {
            String offerInstId = querySceneInstService.getSceneInst(data.getSceneInstId()).getRootInstId();
            List<KiteProdInst> prodInstList = querySceneInstService
                .listProdInstsFromGiftOfferInst(data.getCustId(), offerInstId);
            // 主产品的型号联动对讲终端/座充/电池/背夹/对讲耳机的型号,并且型号值不等于POC060
            prodInstList.forEach(prodInst -> {
                if (KiteStringUtils.equalsAny(prodInst.getSpecId(), ProdCateUtil.getSubMemberProdId(ProdCateUtil.GIFT_SZDJ_PROD))) { //对讲终端
                    linkModelNum(attr, data, prodInst); //型号
                }
                else if (KiteStringUtils.equalsAny(prodInst.getSpecId(), "60000032", "60000030")) { //座充/背夹
                    linkModelNumWithOutAdapterTerminal(attr, data, prodInst); //型号
                }
                else if (KiteStringUtils.isEqual("60000031", prodInst.getSpecId())) { //电池
                    dealDcModelAttr(attr, data, prodInst);
                }
                else if (KiteStringUtils.isEqual("60000029", prodInst.getSpecId())) { //对讲耳机
                    dealDjModelAttr(attr, data, prodInst);
                }
                else if (KiteStringUtils.equalsAny( prodInst.getSpecId(),"63249386","63249558")) { //配件及其他，主控板
                    linkModelNum(attr, data, prodInst);
                }
                else if (KiteStringUtils.isEqual("50000027", prodInst.getSpecId())) { //应急调度套件-平台应用
                    linkPlatformApplicationModelNum(attr, data, prodInst);
                }
            });

            KiteOfferInst giftOfferInst = querySceneInstService.getGiftOfferInst(data.getSceneInstId());
            String cateId = CuccPosServiceUtils.getCateId(data.getSceneInstId(), data.getCustId());
            String offerId = giftOfferInst.getSpecId();
            if("2004109".equals(cateId) && "30000281".equals(offerId)){
                linkDealPrice(attr, inst, data);
            }else {
                dealSalePriceAndSettlementPrice(attr, inst, data); //处理销售价和结算价
            }
        }
    }

    private void linkDealPrice(KiteAttr attr, KiteInst inst, AttrData data){
        //销售价
        KiteAttr salePriceAttr = inst.getAttr("200004107");
        //结算价
        KiteAttr settlePriceAttr = inst.getAttr("200004108");

        if(Objects.nonNull(salePriceAttr)){
            String salePrice = AttrValueCache.getAttrValueByAttrValueName(salePriceAttr.getAttrId(), attr.getValueDesc());
            operateInstAttrService.setAttrValue(inst, "200004107", salePrice, data.getSceneInstId(), null);
        }
        if(Objects.nonNull(settlePriceAttr)){
            String settlePrice = AttrValueCache.getAttrValueByAttrValueName(settlePriceAttr.getAttrId(), attr.getValueDesc());
            operateInstAttrService.setAttrValue(inst, "200004108", settlePrice, data.getSceneInstId(), null);
        }
    }

    /**
     * 处理销售价和结算价
     *
     * @param attr
     * @param inst
     * @param data
     */
    private void dealSalePriceAndSettlementPrice(KiteAttr attr, KiteInst inst, AttrData data) {
        if (KiteStringUtils.isEqual(attr.getValue(), "110006936")) { //雁飞Cat1-POC-001
            // 标准销售价
            operateInstAttrService.setAttrValue(inst, "200004107", "254", data.getSceneInstId(), null);
            // 标准结算价
            operateInstAttrService.setAttrValue(inst, "200004108", "242", data.getSceneInstId(), null);
        }
        else if (KiteStringUtils.isEqual(attr.getValue(), "100007525")) { //POC020
            // 标准销售价
            operateInstAttrService.setAttrValue(inst, "200004107", "358", data.getSceneInstId(), null);
            // 标准结算价
            operateInstAttrService.setAttrValue(inst, "200004108", "320", data.getSceneInstId(), null);
        }
        else if (KiteStringUtils.isEqual(attr.getValue(), "100007526")) { //POC030
            // 标准销售价
            operateInstAttrService.setAttrValue(inst, "200004107", "584", data.getSceneInstId(), null);
            // 标准结算价
            operateInstAttrService.setAttrValue(inst, "200004108", "525", data.getSceneInstId(), null);
        }
        else if (KiteStringUtils.isEqual(attr.getValue(), "100007527")) { //POC040
            // 标准销售价
            operateInstAttrService.setAttrValue(inst, "200004107", "678", data.getSceneInstId(), null);
            // 标准结算价
            operateInstAttrService.setAttrValue(inst, "200004108", "610", data.getSceneInstId(), null);
        }
        else if (KiteStringUtils.isEqual(attr.getValue(), "100007528")) { //POC050
            // 标准销售价
            operateInstAttrService.setAttrValue(inst, "200004107", "1799", data.getSceneInstId(), null);
            // 标准结算价
            operateInstAttrService.setAttrValue(inst, "200004108", "1685", data.getSceneInstId(), null);
        }
        else if (KiteStringUtils.isEqual(attr.getValue(), "100007529")) { //POC060
            // 标准销售价
            operateInstAttrService.setAttrValue(inst, "200004107", "1185", data.getSceneInstId(), null);
            // 标准结算价
            operateInstAttrService.setAttrValue(inst, "200004108", "1053", data.getSceneInstId(), null);
        }
        //给标准结算价赋默认值，方便规则中心判断是否需要上传oop
        inst.listAttrs().stream().forEach(kiteAttr -> {
            if (KiteStringUtils.isEqual(kiteAttr.getFieldName(),"200004108")){
                kiteAttr.setDefaultValue(kiteAttr.getValue());
            }
        });
    }

    private void dealDjModelAttr(KiteAttr attr, AttrData data, KiteProdInst prodInst) {
        KiteAttr djModelAttr = prodInst.getAttr("200002772"); //型号
        List<AttrValue> attrValues = AttrValueCache.get(djModelAttr.getAttrId()); //下拉列表规格数据
        if (KiteStringUtils.isEqual("100007529", attr.getValue())) { //主产品型号选择POC060时,对讲耳机的型号更新下拉值
            if (!KiteObjectUtils.isEmpty(djModelAttr)) {
                attrValues = attrValues.stream()
                    .filter(t -> KiteStringUtils.equalsAny(t.getAttrValue(), "110007336", "110007337", "110007338"))
                    .collect(Collectors.toList()); //POC060（普通版）/POC060（空气导管版）/POC060（手持版）
                if (CollectionUtils.isNotEmpty(attrValues)) {
                    djModelAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
                }
                djModelAttr.setIsEdit("T");
                String extParam = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "entry");
                boolean flag = true;
                if ("sceneTempl".equals(data.getExtAttributes().get("entry")) || "sceneTempl".equals(extParam)) {
                    flag = false;
                }
                if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(data.getServiceOfferId()) && !KeyConsts.IFTRUE_T
                    .equals(querySceneInstService
                        .getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))) {
                    flag = false;
                }
                if (flag) {
                    operateInstAttrService
                        .setAttrValue(prodInst, "200002772", "110007336", data.getSceneInstId(), null);
                }
            }
        }
        else {
            djModelAttr.setIsEdit("F");
            djModelAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
            linkModelNumWithOutAdapterTerminal(attr, data, prodInst); //型号
        }
    }

    private void dealDcModelAttr(KiteAttr attr, AttrData data, KiteProdInst prodInst) {
        KiteAttr dcModelAttr = prodInst.getAttr("200002772"); //型号
        List<AttrValue> attrValues = AttrValueCache.get(dcModelAttr.getAttrId()); //下拉列表规格数据
        if (KiteStringUtils.isEqual("100007528", attr.getValue())) { //主产品型号选择POC050时,电池的型号更新下拉值
            if (!KiteObjectUtils.isEmpty(dcModelAttr)) {
                attrValues = attrValues.stream()
                    .filter(t -> KiteStringUtils.equalsAny(t.getAttrValue(), "110007339", "110007340"))
                    .collect(Collectors.toList()); //POC050（普通版）/POC050（防爆版）
                if (CollectionUtils.isNotEmpty(attrValues)) {
                    dcModelAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
                }
                dcModelAttr.setIsEdit("T");
                String extParam = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "entry");
                boolean flag = true;
                if ("sceneTempl".equals(data.getExtAttributes().get("entry")) || "sceneTempl".equals(extParam)) {
                    flag = false;
                }
                if (!ServiceOfferConsts.SERVICE_OFFER_ORDER.equals(data.getServiceOfferId()) && !KeyConsts.IFTRUE_T
                    .equals(querySceneInstService
                        .getExtParameterValue(data.getSceneInstId(), LocalKeyConsts.BUSI_CHANGE_SCENE))) {
                    flag = false;
                }
                if (flag) {
                    operateInstAttrService
                        .setAttrValue(prodInst, "200002772", "110007339", data.getSceneInstId(), null);
                }
            }
        }
        else {
            dcModelAttr.setIsEdit("F");
            dcModelAttr.setAttrValues(KiteBeanUtils.copyPropsForList(attrValues, KiteAttrValue.class));
            linkModelNumWithOutAdapterTerminal(attr, data, prodInst); //型号
        }
    }

    private void linkModelNum(KiteAttr attr, AttrData data, KiteProdInst prodInst) {
        if (!KiteObjectUtils.isEmpty(prodInst.getAttr("200002772"))) { //型号
            operateInstAttrService.setAttrValue(prodInst, "200002772", attr.getValue(), data.getSceneInstId(), null);
        }
    }

    private void linkModelNumWithOutAdapterTerminal(KiteAttr attr, AttrData data, KiteProdInst prodInst) {
        if (!KiteObjectUtils.isEmpty(prodInst.getAttr("200002772")) && !KiteStringUtils
            .isEqual("110006936", attr.getValue())) { //型号
            KiteAttr kiteAttr = prodInst.getAttr("200002772");
            kiteAttr.setIsEdit("F");
            operateInstAttrService.setAttrValue(prodInst, "200002772", attr.getValue(), data.getSceneInstId(), null);
        }
        else if (!KiteObjectUtils.isEmpty(prodInst.getAttr("200002772")) && KiteStringUtils
            .isEqual("110006936", attr.getValue())) {
            KiteAttr kiteAttr = prodInst.getAttr("200002772");
            kiteAttr.setIsEdit("T");
            operateInstAttrService.setAttrValue(prodInst, "200002772", "100007525", data.getSceneInstId(), null);
        }
    }

    private void linkPlatformApplicationModelNum(KiteAttr attr, AttrData data, KiteProdInst prodInst) {
        if (!KiteObjectUtils.isEmpty(prodInst.getAttr("200002772")) && KiteStringUtils
            .equalsAny(attr.getValue(), "110006936", "100007525")) { //型号
            KiteAttr kiteAttr = prodInst.getAttr("200002772");
            kiteAttr.setIsEdit("F");
            operateInstAttrService.setAttrValue(prodInst, "200002772", "110015002", data.getSceneInstId(), null);
        }
        else if (!KiteObjectUtils.isEmpty(prodInst.getAttr("200002772")) && KiteStringUtils
            .equalsAny(attr.getValue(), "100007526", "100007528")) {
            KiteAttr kiteAttr = prodInst.getAttr("200002772");
            kiteAttr.setIsEdit("F");
            operateInstAttrService.setAttrValue(prodInst, "200002772", "110015003", data.getSceneInstId(), null);
        }
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }
}
